﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.U2D;

/// <summary>
/// 从图集中获取一个 sprite 然后设置给 image
/// </summary>
//[ExecuteInEditMode]
public class BhvAtlasFrame : MonoBehaviour
{
    public SpriteAtlas atlas;
    public Sprite defaultSprite;
    [Tooltip("icon_*  可以获取 icon_1, icon_3 的帧图名和 index")]
    public string atlasNameTemplate = "*";


    [HideInInspector]
    [Tooltip("索引模式，启用后可以使用模板名称字符来设置 index")]
    public bool indexMode = false;

    [HideInInspector]
    private int _index = 0;
    [HideInInspector]
    public int index
    {
        get
        {
            return _index;
        }
        set
        {
            if (value < 0) value = 0;
            if (value > this.indexMax) value = this.indexMax;
            this._index = value;
            this.frameName = this.GetNameFromTemplate(value);
            _index = value;
        }
    }

    [HideInInspector]
    public int indexMax = 99999;

    [HideInInspector]
    private string _frameName = "";

    [HideInInspector]
    public string frameName
    {
        get
        {
            return _frameName;
        }
        set
        {
            ResetImageSprite(value);
            _frameName = value;

        }
    }



    private string ResetImageSprite(string name)
    {
        var frame = atlas.GetSprite(name);
        if (frame == null && defaultSprite)
        {
            frame = defaultSprite;
            this._index = 0;
            return frame.name;
        }
        GetComponent<SpriteRenderer>().sprite = frame;
        return frame.name;

    }

    private string GetNameFromTemplate(int index)
    {
        return atlasNameTemplate.Replace("*", index.ToString());
    }

    public void SetRandomIndex(int min, int max)
    {
        index = Random.Range(min, max);
    }

    public void SetRandomFrameName()
    {
        int index = Random.Range(0, atlas.spriteCount);
        Sprite[] sprites = new Sprite[atlas.spriteCount];
        atlas.GetSprites(sprites);
        if (index >= atlas.spriteCount) index = atlas.spriteCount - 1;
        frameName = sprites[index].name.Replace("(Clone)", "");
    }



}
